//
// Created by fh on 2021/6/2.
//

#include "LinkQueue.h"

/* 插入元素e为q的新的队尾元素 */
Status LinkQueueEnQueue(LinkQueue *q,int e) {
    if (q == NULL) {
        return ERROR;
    }
    QNode *node = (QNode *) malloc(sizeof(QNode));
    if (node == NULL) {
        return ERROR;
    }
    node->data = e;
    node->next = NULL;

    q->rear->next = node;
    q->rear = node;
    return OK;
}

/* 若队列不空，删除q的队头元素，用e返回其值 */
Status LinkQueueDeQueue(LinkQueue *q,int *e) {
    if (q->rear == q->front) {
        return ERROR; /*链队列是空的*/
    }
    QNode *delete = q->front->next;
    *e = delete->data;
    q->front->next = delete->next;
    // 要考虑删除后尾指针的问题
    if (q->rear == delete) {
        q->rear = q->front;
    }
    free(delete);
    delete = NULL;
    return OK;
}

/* 遍历链队列 */
Status LinkQueueDisplay(const LinkQueue *q) {
    if (q == NULL) {
        return ERROR;
    }
    printf("遍历链队列: ");
    QNode *p = q->front->next;
    while (p != NULL) {
        printf("%d ",p->data);
        p = p->next;
    }
    printf("\n");
    return OK;
}

/* 链队列生成和初始化 */
LinkQueue *LinkQueueCreateAndInit() {
    LinkQueue *q = (LinkQueue *) malloc(sizeof(LinkQueue));
    if (q == NULL) {
        return NULL;
    }
    QNode *head = (QNode *) malloc(sizeof(QNode));
    if (head == NULL) {
        return NULL;
    }
    head->data = -1;
    head->next = NULL;

    q->front = head;
    q->rear = head;
    return q;
}

/* 测试demo */
void linkQueueTestDemo() {
    printf("--------------------------- 链队列生成和初始化 ------------------------\n");
    LinkQueue *q = (LinkQueue *)LinkQueueCreateAndInit();
    if (q == NULL) {
        return;
    }
    printf("--------------------------- 链队列进队 ------------------------\n");
    LinkQueueEnQueue(q,4);
    LinkQueueDisplay(q);

    LinkQueueEnQueue(q,6);
    LinkQueueDisplay(q);

    LinkQueueEnQueue(q,9);
    LinkQueueDisplay(q);

    LinkQueueEnQueue(q,1);
    LinkQueueDisplay(q);

    printf("--------------------------- 链队列出队 ------------------------\n");
    int a = 0;
    LinkQueueDeQueue(q,&a);
    LinkQueueDisplay(q);
}